package com.ruoyi.web.job;

import com.ruoyi.activity.service.IActivityService;
import com.ruoyi.activity.service.IContestService;
import com.ruoyi.blog.service.BlogService;
import com.ruoyi.common.config.MyThreadPoolConfig;
import com.ruoyi.common.constant.ActivitysConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.model.activity.Activity;
import com.ruoyi.model.blog.Blog;
import com.ruoyi.model.contest.Contest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author : 张怀秋
 **/
@Component
public class ContestJobUpdateViewCountController extends BaseController {
    @Resource
    private RedisCache redisCache;

    @Resource
    private MyThreadPoolConfig config;

    @Resource
    private IActivityService activityService;

    @Resource
    private IContestService contestService;

    @Resource
    private BlogService blogService;

    @Scheduled(cron = "*/10 * * * * ?")
    public void updateViewCount() {
        ThreadPoolExecutor executor = config.threadPoolExecutor();
        //1.定时任务同步redis中的竞赛浏览量进入数据库
        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            //获取redis中的竞赛浏览量
            Map<String, Object> contestMap = redisCache.getCacheMap(ActivitysConstant.CONTEST_KEY);
            //保存到数据库
            List<Contest> contestList = contestMap.entrySet().stream().map(contest -> new Contest(contest.getKey(), (Integer) contest.getValue())).collect(Collectors.toList());
            contestService.updateBatchById(contestList);
        }, executor);
        //2.定时任务同步redis中的活动浏览量进入数据库
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            //获取到redis的中活动浏览量
            Map<String, Object> activityMap = redisCache.getCacheMap(ActivitysConstant.ACTIVITY_KEY);
            List<Activity> activityList = activityMap.entrySet().stream().map(item -> new Activity(item.getKey(), (Integer) item.getValue())).collect(Collectors.toList());
            activityService.updateBatchById(activityList);
        }, executor);
        //3.定时任务同步redis中的文章
        CompletableFuture<Void> voidCompletableFuture2 = CompletableFuture.runAsync(() -> {
            //获取到redis的中活动浏览量
            Map<String, Object> blogMap = redisCache.getCacheMap(ActivitysConstant.BLOG_KEY);
            List<Blog> blogList = blogMap.entrySet().stream().map(item -> new Blog(item.getKey(), (Integer) item.getValue())).collect(Collectors.toList());
            blogService.updateBatchById(blogList);
        }, executor);
        CompletableFuture.allOf(voidCompletableFuture1, voidCompletableFuture, voidCompletableFuture2).join();
    }
}
